#!/usr/bin/env python

import subprocess
import traceback
import pdb
import argparse
from config import zmqports
from time import sleep
from datacenter import IntegrateTestServer,EchoServer
from webserver import WebServer
from logger_server import LoggerServerWrapper,ZmqPublisher


class DummyMachine2(object):
	def __init__(self,ttc_config,web_port,is_echo_server,echo_server_map):

		self.pub_logger_endppint_ = "tcp://*:" + str(zmqports.LOGGER_PUB_PORT)
		self.pub_ts_endpoint_ = "tcp://*:" + str(zmqports.TESTSERVER_PORT_PORT)
		self.pub_ws_endpoint_ = "tcp://*:" + str(zmqports.WEBSERVER_PUB_PORT)
		# Create publisher for logger/testserver/webserver
		self.pub_logger_ = ZmqPublisher( endpoint=self.pub_logger_endppint_, identity='Logger')
		self.pub_ts_ = ZmqPublisher(endpoint=self.pub_ts_endpoint_, identity='TestServer')
		self.pub_ws_ = ZmqPublisher(endpoint=self.pub_ws_endpoint_, identity='CommandList')
		# Create server
		self.web_server_ = WebServer(web_port,publisher=self.pub_ws_)
		self.logger_server_ = LoggerServerWrapper(publisher=self.pub_logger_,config_file='config/logger_config.json')
		if is_echo_server:
			self.test_server_ = EchoServer(ttc_config,publisher=self.pub_ts_,echo_server_map=echo_server_map)
		else:
			self.test_server_ = IntegrateTestServer(ttc_config,publisher=self.pub_ts_)


	def run(self):
		print("Begin to launch dummy_machine2 service thread...")
		self.web_server_.start()
		self.test_server_.start()
		self.logger_server_.start()
		print("Launch dummy_machine2 finish.")
		while True: sleep(1)


def createVirtualIP(ip_list):
	# TODO create a class
	for ip in ip_list:
		# FIX ME: check return value. Current method is invalid.
		ret = subprocess.call(["sudo","ifconfig","lo0","alias",ip])
		if ret!=0 :
			print("Failed to create Alias-IP. "+ip)
			raise Exception("Invalid alias IP. "+ip);


def releaseVirtualIP(ip_list):
	for ip in ip_list:
		# FIX ME: check return value. Current method is invalid.
		ret = subprocess.call(["sudo","ifconfig","lo0","-alias",ip])
		if ret!=0 :
			print("Failed to release Alias-IP. "+ip)



#================ Main ==========================
if __name__=="__main__":
	# Configuration
	parser = argparse.ArgumentParser()
	parser.add_argument('-tcs', '--testcase_server', help='Run all test_case for current TM.', type=bool, default=False)
	parser.add_argument('-es_mt', '--echo_server_map', help='Choose default maptable for echo server.', type=str, default="test_case_default")
	parser.add_argument('-ap', '--arm_port', help='port for arm board.', type=int, default=7600)
	parser.add_argument('-pp', '--power_port', help='port for power board.', type=int, default=8082)
	parser.add_argument('-dp', '--dut_port', help='port for dut board.', type=int, default=8081)
	parser.add_argument('-wp', '--web_port', help='port for web server.', type=int, default=9000)
	parser.add_argument('-tp', '--trigger_port', help='port for trigger statemachine(Echo Server Ignored).', type=int, default=6480)
	parser.add_argument('-smhp', '--sm_heartbeat_port', help='port for get heartbear of statemachine(Echo Server Ignored).', type=int, default=6580)
	parser.add_argument('-smsp', '--sm_state_port', help='port for get state(PUB) of statemachine(Echo Server Ignored).', type=int, default=6880)
	parser.add_argument('-seqp', '--sequencer_port', help='port for get state(PUB) of sequencer(Echo Server Ignored).', type=int, default=6250)

	parser.add_argument('-u1', '--uut1_ip', help='channel for dut 1.', type=str, default="169.254.1.30")
	parser.add_argument('-u2', '--uut2_ip', help='channel for dut 2.', type=str, default="169.254.1.31")

	args = parser.parse_args()

	# Build data
	server_ip_list = [args.uut1_ip,args.uut2_ip]
	server_port_list = {"arm_port":args.arm_port,"power_port":args.power_port,"dut_port":args.dut_port}
	is_echo_server = not args.testcase_server
	echo_server_map_table = args.echo_server_map
	ttc_config = {
		"ip_list":server_ip_list,
		"port_list":server_port_list,
		"trigger_port":args.trigger_port,
		"sm_port":args.sm_heartbeat_port,
		"sm_state_port":args.sm_state_port,
		"sequencer_port":args.sequencer_port,
	}

	web_port = args.web_port
	# Do Work
	try:
		createVirtualIP(server_ip_list)

		dummy_machine2 = DummyMachine2(ttc_config=ttc_config,web_port=web_port,is_echo_server=is_echo_server,echo_server_map=echo_server_map_table)
		dummy_machine2.run()
	except Exception as e:
		traceback.print_exc()
	finally:
		releaseVirtualIP(server_ip_list)
